<template>
  <!-- 新日账单明细 -->
  <div class="home-page-container">
    <!-- search 查询 -->
    <el-card shadow="never">
      <mer-search :searchConfig="formConfig" :searchBar="searchBar" @search="search" @reset="reset(initQuery)" @changeTime="(value, model)=>changeQueryTime(value, model)" :loading="tableLoading" :isLayout="true"></mer-search>
    </el-card>
    <!-- table 表格 -->
    <el-card shadow="never">
      <mer-table :loading="tableLoading" :tableConfig="tableConfig" :tableData="tableData" :pagination="pagination" :layout="'total, sizes, prev, pager, next'" :pageSizes="[10]" @SizeChange="handleSizeChange" @PageChange="pageChange" :hasIndex="true">
        <template slot="handler" slot-scope="{row}">
          <div class="btns">
            <el-button size="mini" @click="goShopCouponDetail(row)" v-if="row.activeType===3">查看</el-button>
            <el-button size="mini" @click="goShopCouponEdit(row)" v-if="row.activeType===3&&row.activeStatus===5">编辑</el-button>
            <el-button size="mini" @click="updateCouponState(row, 3)" v-if="row.activeType===3&&row.activeStatus===5">取消</el-button>
            <el-button size="mini" @click="updateCouponState(row, 4)" v-if="row.activeType===3&&row.activeStatus===1">停止</el-button>
            <el-button size="mini" @click="showDetail(row)" v-if="[1,2,4].includes(row.activeStatus)">效果详情</el-button>
          </div>
        </template>
      </mer-table>
    </el-card>
  </div>
</template>
<script>
import listPage from '@/mixins/listPage'
import queryMix from '@/views/finance/mixins/query'
import { activeList, activitySelect, updateCouponState } from '@/api/market'

// 查询表单配置
let formConfig = [
  { label: '当前油站', type: 'select', modelName: 'gasId', placeholder: '全部', selectOptions: [], define: true, selectLabel: 'gasName', selectValue: 'gasId' },
  { label: '创建时间', type: 'date', modelName: 'tradeTime', model: '', dateType: 'datetimerange', format: 'yyyy-MM-dd HH:mm:ss', pickerOptions: {}, clearable: false },
  { label: '活动时间', type: 'date', modelName: 'activeTime', model: '', dateType: 'datetimerange', format: 'yyyy-MM-dd HH:mm:ss', pickerOptions: {}, clearable: true },
  /*{ label: '操作人', type: 'input', modelName: 'createUser', placeholder: '请输入操作人', maxlength: 100 },*/
  { label: '营销类型', type: 'select', modelName: 'activeType', placeholder: '全部', selectOptions: [], define: true, selectLabel: 'value', selectValue: 'key' },
  { label: '活动名称', type: 'input', modelName: 'activityName', placeholder: '请输入活动名称', maxlength: 100 },
  { label: '活动状态', type: 'select', modelName: 'activityState', placeholder: '全部', selectOptions: [], define: true, selectLabel: 'value', selectValue: 'key' }
]
// 表格参数配置
let tableConfig = [
  { label: '活动类型', prop: 'activeTypeName', width: 150 },
  { label: '活动名称', prop: 'activeName', width: 200 },
  /*{ label: '发送状态', prop: 'taskStatusName', width: 150 },*/
  { label: '活动状态', prop: 'activeStatusName', width: 150 },
  { label: '活动开始时间', prop: 'startTime', width: 150 },
  { label: '活动结束时间', prop: 'endTime', width: 150 },
  { label: '创建时间', prop: 'createTime', width: 150 },
  { label: '发放/领取券数量', prop: 'couponNum', width: 136 },
  /*{ label: '发放人数', prop: 'sendNum', width: 136 },*/
  { label: '已核销券数量', prop: 'couponUsedNum', width: 136 },
  /*{ label: '参与人数', prop: 'joinUserNum', width: 136 },*/
  { label: '券订单流水', prop: 'totalOrderAmount', width: 136 },
  { label: '创建人', prop: 'createUser', width: 136 },
  { label: '油站', prop: 'gasName', width: 136 },
  { label: '操作', slot: 'handler', fixed: 'right', width: 250 }
]
export default {
  mixins: [listPage, queryMix],
  data () {
    return {
      tradeTime: '',
      formConfig: formConfig,
      tableConfig: tableConfig,
      categoryTypes: [],
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate.getTime()
          if (maxDate) {
            this.selectDate = ''
          }
        },
        disabledDate: (time) => {
          if (this.selectDate !== '') {
            const one = 7 * 24 * 3600 * 1000
            const minTime = this.selectDate - one
            const maxTime = this.selectDate + one
            return time.getTime() < minTime || time.getTime() > maxTime
          }
        }
      }
    }
  },
  created () {
    this.initPage()
  },
  methods: {
    initPage () {
      this.initQuery()
      this.getAllQueryProps()
    },
    // 设置默认查询条件，暂无默认时间间隔
    initQuery () {
      this.tradeTime = ''
      this.initTime('tradeTime', 6, 'searchBar', true, 'startTime', 'endTime')
      this.formConfig[this.findConfigIndex(this.formConfig, 'tradeTime')].model = this.tradeTime
      this.formConfig[this.findConfigIndex(this.formConfig, 'tradeTime')].pickerOptions = this.pickerOptions
      this.formConfig[this.findConfigIndex(this.formConfig, 'activeTime')].model = ''
      this.formConfig[this.findConfigIndex(this.formConfig, 'activeTime')].pickerOptions = this.pickerOptions
      this.changeTime('', 'searchBar', 'activeStartTime', 'activeEndTime')
    },
    changeQueryTime (value, model) {
      if (model === 'activeTime') {
        this.changeTime(value, 'searchBar', 'activeStartTime', 'activeEndTime')
      } else {
        this.changeTime(value, 'searchBar', 'startTime', 'endTime')
      }
    },
    getAllQueryProps () {
      this.getQueryStatus()
      //获取油站
      this.getAllGasStations()
    },
    showDetail (row) {
      this.$router.push({ path: '/marketCenter/marketActivityDetail', query: { mark: row.id } })
    },
    // 获取查询条件：交易类型
    async getQueryStatus () {
      try {
        const { code, result } = await activitySelect()
        if(code !== 200) return
        const { ActivityStatusEnum, ActivityTypeEnum, codeToType } = result
        this.formConfig[this.findConfigIndex(this.formConfig,'activityState')].selectOptions = ActivityStatusEnum
        this.formConfig[this.findConfigIndex(this.formConfig,'activeType')].selectOptions = ActivityTypeEnum
        const { gasId, interestCode } = this.$route.query
        if (gasId) this.$set(this.searchBar, 'gasId', gasId)
        if (interestCode) this.$set(this.searchBar, 'activeType', codeToType[interestCode] || '')
        this.initList(activeList, false)
      }catch(err){
        console.log(err)
      }
    },
    /**
     * 店铺优惠券活动修改状态：取消/停止
     */
    updateCouponState (params, state) {
      this.$confirm(`确定${state === 3 ? '取消' : '停止'}此活动吗?`, '确认提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await updateCouponState({ state, activeId: params.id })
        this.refresh()
        if (res.code !== 200) return
        this.$message.success('操作成功')
      }).catch(() => {
      })
    },
    goShopCouponDetail (params) {
      this.$router.push({
        name: 'shopCouponDetail',
        query: {
          activeId: params.id
        }
      })
    },
    goShopCouponEdit (params) {
      this.$router.push({
        name: 'editShopCoupon',
        query: {
          activeId: params.id
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .home-page-container {
    margin-top: 20px;
  }

  .el-card {
    margin-top: 10px;
  }

  .btns {
    text-align: left;
    .el-button {
      margin: 3px;
    }
  }
</style>
